package com.bachelor.community.controller;

import com.bachelor.community.annotation.UnInterception;
import com.bachelor.community.model.entity.Answer;
import com.bachelor.community.model.entity.Collection;
import com.bachelor.community.service.intf.AnswerService;
import com.bachelor.community.service.intf.CollectionService;
import com.bachelor.community.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class AnswerController {
    @Resource
    private AnswerService answerService;
    @Resource
    private CollectionService collectionService;

    @GetMapping("/questions/{questionId}/answers")
    @UnInterception
    public Result listAnswers(@PathVariable Long questionId, @RequestParam("order") String order) {
        return Result.succeed("200", answerService.listAnswers(questionId, order));
    }

    @GetMapping("/answers")
    public Result listAnswersByUserId(@RequestParam(value = "offset", required = false) Integer currentPage,
                                      @RequestParam(value = "limit", required = false) Integer pageSize,
                                      @RequestParam(value = "userId", required = false) Integer userId) {
        return Result.succeed("200", answerService.listAnswersByUserId(currentPage, pageSize, userId));
    }

    @PostMapping("/questions/{questionId}/answers")
    public Result insertAnswer(@PathVariable Long questionId, @RequestBody Answer answer) {
        return Result.succeed("201", answerService.insertAnswer(questionId, answer));
    }

    @PatchMapping("/answers/{answerId}")
    public Result partialUpdateAnswer(@PathVariable Integer answerId, @RequestBody Answer answer) {
        return Result.succeed("200", answerService.partialUpdateAnswer(answerId, answer));
    }

    @DeleteMapping("/answers/{answerId}")
    public Result removeAnswer(@PathVariable Integer answerId) {
        QueryWrapper<Collection> collectionQueryWrapper = new QueryWrapper<>();
        collectionQueryWrapper.eq("answer_id", answerId);
        collectionService.remove(collectionQueryWrapper);
        return Result.succeed("204", answerService.removeById(answerId));
    }
}
